
import {loadJson} from "../network/fetcher.js";
import {feature} from "topojson-client";
import {isMobile} from "../util/context.js";
import {report} from "../report.js";
import {$} from "../util/seq.js";

const mobile = isMobile();

/**
 * @param resource the GeoJSON resource's URL
 * @param cancel
 * @returns {Promise} a promise for GeoJSON topology features: {boundaryLo:, boundaryHi:}
 */
export function buildMesh(resource, cancel) {
    report.status("Downloading...");
    const files = [];
    files.push(loadJson(resource));

    return Promise.all(files).then(([topo]) => {
        if (cancel.requested) return null;
        console.time("building meshes");
        const o = topo.objects;
        const coastLo = feature(topo, mobile ? o.coastline_tiny : o.coastline_110m);
        const coastHi = feature(topo, mobile ? o.coastline_110m : o.coastline_50m);
        const lakesLo = feature(topo, mobile ? o.lakes_tiny : o.lakes_110m);
        const lakesHi = feature(topo, mobile ? o.lakes_110m : o.lakes_50m);
        const riversLo = feature(topo, mobile ? o.rivers_tiny : o.rivers_110m);
        const riversHi = feature(topo, mobile ? o.rivers_110m : o.rivers_50m);

        console.timeEnd("building meshes");
        return {
            coastLo: coastLo,
            coastHi: coastHi,
            lakesLo: lakesLo,
            lakesHi: lakesHi,
            riversLo: riversLo,
            riversHi: riversHi,
        };
    });
}

/**
 * @param meshAgent
 * @param {Handle} topology_url
 */
export function defineMeshBuilder(meshAgent, topology_url) {

    function build(topology) {
        meshAgent.submit(function() {
            return buildMesh(topology, this.cancel);
        });
    }

    topology_url.on($`change`, build);
}
